﻿/*
 * Server.cs
 * 
 * Copyright (C) 2011 Elena Shishkina
 * 
 * This file is part of ServerInventory.
 * 
 * ServerInventory is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ServerInventory is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ServerInventory.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace ServerInventory
{
    public class Server: Data
    {
        public override void Process()
        {
            var mode = param("mode");
            switch (mode)
            {
                case "edit": Edit(); break;
                case "remove": Remove(); break;
                case "add": Add(); break;
                case "full": Full(); break;
                case "ips": GetIpList(); break;
                default: LoadData(); break;
            }
        }

        private void LoadData()
        {
            var rack_id = GetRackId();
            using (var conn = DbConnect())
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"select d.id as dc_id, d.name as dc, r.name as rack, i.*, v.name as vendor, v.color as vcolor, srv_ips.ips as srvip 
from inventory i 
left join racks r on r.id = i.rack_id
left join dcs d on d.id = r.dc_id
left join vendors v on i.vendor_id = v.id
left join
(select distinct server_id,
(stuff((select ',' + ip from server_ips i2 where i1.server_id = i2.server_id order by ip
for xml path(''), type, root).value('root[1]','nvarchar(max)'),1,1,'')) as ips
from server_ips i1) as srv_ips
on srv_ips.server_id = i.id
where r.id = @rack
union all
select null, null, null, rack_id, 'reserved', null, null, null, null, null, null, cast(unit as varchar), null, null, null, null, null, null, null, null, null
from reserved_units where rack_id = @rack
order by dc, rack, i.name";
                    cmd.Parameters.AddWithValue("@rack", rack_id);
                    ToJson(cmd);
                }
            }
        }

        private void GetIpList()
        {
            using (var conn = DbConnect())
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"select
i.ip,
coalesce(s.name, v.name, s.model) as cname,
s.name as name,
v.name as vendor,
s.model,
r.name as rack,
d.name as dc
from server_ips i
left join inventory s on i.server_id = s.id
left join vendors v on s.vendor_id = v.id
left join racks r on s.rack_id = r.id
left join dcs d on r.dc_id = d.id
order by 
		 CAST(PARSENAME(ip, 4) AS INT),
         CAST(PARSENAME(ip, 3) AS INT),
         CAST(PARSENAME(ip, 2) AS INT),
         CAST(PARSENAME(ip, 1) AS INT)";
                    ToJson(cmd);
                }
            }
        }

        private void Full()
        {
            using (var conn = DbConnect())
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"select d.id as dc_id, d.name as dc, r.name as rack, i.*, v.name as vendor, v.color as vcolor, srv_ips.ips as srvip 
from inventory i 
left join racks r on r.id = i.rack_id
left join dcs d on d.id = r.dc_id
left join vendors v on i.vendor_id = v.id
left join
(select distinct server_id,
(stuff((select ',' + ip from server_ips i2 where i1.server_id = i2.server_id order by ip
for xml path(''), type, root).value('root[1]','nvarchar(max)'),1,1,'')) as ips
from server_ips i1) as srv_ips
on srv_ips.server_id = i.id
order by dc, rack, i.name";
                    ToJson(cmd);
                }
            }
        }

        private void Add()
        {
            var rack_id = GetRackId();
            var pstate = GetPstate();
            var ips = GetIps();
            using (var conn = DbConnect())
            {
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    using (var cmd = conn.CreateCommand())
                    {
                        cmd.Transaction = trans;
                        cmd.CommandText = "insert into inventory (rack_id, name, vendor_id, model, type, sn, [in], pusage, pstate, units, mgmtip, notes, color, @responsible) values (@rack_id, @name, @vendor_id, @model, @type, @sn, @in, @pusage, @pstate, @units, @mgmtip, @notes, @color, @responsible); select @@identity;";
                        cmd.Parameters.AddWithValue("@rack_id", rack_id);
                        cmd.Parameters.AddWithValue("@name", param("name"));
                        cmd.Parameters.AddWithValue("@vendor_id", param("vendor_id"));
                        cmd.Parameters.AddWithValue("@model", param("model"));
                        cmd.Parameters.AddWithValue("@type", param("type"));
                        cmd.Parameters.AddWithValue("@sn", param("sn"));
                        cmd.Parameters.AddWithValue("@in", param("in"));
                        cmd.Parameters.AddWithValue("@pusage", param("pusage"));
                        cmd.Parameters.AddWithValue("@pstate", pstate);
                        cmd.Parameters.AddWithValue("@units", param("units"));
                        cmd.Parameters.AddWithValue("@mgmtip", param("mgmtip"));
                        cmd.Parameters.AddWithValue("@notes", param("notes"));
                        cmd.Parameters.AddWithValue("@color", param("color"));
                        cmd.Parameters.AddWithValue("@responsible", param("responsible"));

                        var id = cmd.ExecuteScalar().ToString();
                        cmd.CommandText = "delete from server_ips where server_id = @server_id";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@server_id", SqlDbType.Int).Value = id;
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = "insert into server_ips (server_id, ip) values (@server_id, @ip)";
                        cmd.Parameters.Add("@ip", SqlDbType.VarChar).Size = 20;
                        cmd.Prepare();
                        foreach (string ip in ips)
                        {
                            cmd.Parameters["@ip"].Value = ip;
                            cmd.ExecuteNonQuery();
                        }
                        trans.Commit();
                        writer("{\"result\": \"RESULT_OK\", \"id\": \"" + id + "\"}");
                    }
                }
            }
        }

        private void Remove()
        {
            var id = GetId();
            using (var conn = DbConnect())
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "delete from inventory where id = @id";
                    cmd.Parameters.AddWithValue("@id", id);
                    cmd.ExecuteNonQuery();
                }
                ResultOK();
            }
        }

        private void Edit()
        {
            var id = GetId();
            var rack_id = GetRackId();
            var pstate = GetPstate();
            var ips = GetIps();
            using (var conn = DbConnect())
            {

                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    using (var cmd = conn.CreateCommand())
                    {
                        cmd.Transaction = trans;
                        cmd.CommandText = "update inventory set rack_id = @rack_id, name = @name, vendor_id = @vendor_id, model = @model, type = @type, sn = @sn, [in] = @in, pusage = @pusage, pstate = @pstate, units = @units, mgmtip = @mgmtip, notes = @notes, color = @color, responsible = @responsible where id = @id";
                        cmd.Parameters.AddWithValue("@rack_id", rack_id);
                        cmd.Parameters.AddWithValue("@name", param("name"));
                        cmd.Parameters.AddWithValue("@vendor_id", param("vendor_id"));
                        cmd.Parameters.AddWithValue("@model", param("model"));
                        cmd.Parameters.AddWithValue("@type", param("type"));
                        cmd.Parameters.AddWithValue("@sn", param("sn"));
                        cmd.Parameters.AddWithValue("@in", param("in"));
                        cmd.Parameters.AddWithValue("@pusage", param("pusage"));
                        cmd.Parameters.AddWithValue("@pstate", pstate);
                        cmd.Parameters.AddWithValue("@units", param("units"));
                        cmd.Parameters.AddWithValue("@mgmtip", param("mgmtip"));
                        cmd.Parameters.AddWithValue("@notes", param("notes"));
                        cmd.Parameters.AddWithValue("@color", param("color"));
                        cmd.Parameters.AddWithValue("@responsible", param("responsible"));
                        cmd.Parameters.AddWithValue("@id", id);
                        cmd.ExecuteNonQuery();

                        cmd.CommandText = "delete from server_ips where server_id = @server_id";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@server_id", SqlDbType.Int).Value = id;
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = "insert into server_ips (server_id, ip) values (@server_id, @ip)";
                        cmd.Parameters.Add("@ip", SqlDbType.VarChar).Size = 20;
                        cmd.Prepare();
                        foreach (string ip in ips)
                        {
                            cmd.Parameters["@ip"].Value = ip;
                            cmd.ExecuteNonQuery();
                        }

                        trans.Commit();
                        ResultOK();
                    }
                }
            }
        }

        public int GetId()
        {
            return GetInt("id");
        }

        public int GetRackId()
        {
            return GetInt("rack_id");
        }

        public bool GetPstate()
        {
            if (param("pstate") != null) return true;
            else return false;
        }

        public string[] GetIps()
        {
            return param("srvip").Split(',');
        }

        public override void Headers(Data.SetHeaderDelegate callback)
        {
            callback("Content-type", "application/json");
        }
    }
}